<?php
/**
 * Created by PhpStorm.
 * User: djh
 * Date: 2016/11/10
 * Time: 17:53
 */

namespace member\action;
use herosphp\bean\Beans;
use herosphp\core\Log;
use herosphp\http\HttpRequest;
use herosphp\core\Loader;
use herosphp\session\Session;
use herosphp\utils\AjaxResult;
use member\service\RegisterService;
use member\service\LoginService;

Loader::import('member.service.RegisterService');
Loader::import('utils.sms.Cr6868Provider');

class RegAction extends CommonAction{
    public function index(HttpRequest $request){
		if($_POST)
		{
			$this->register($request);
		}
        $ad = Beans::get("information.informationAd.service")->getItem(array('ad_place_key'=>'18574d4e4a60013d9d7e46af6ea2906b'));
        $this->assign('adBanner',$ad);
		$this->setView('reg/reg_index');
    }

	public function register(HttpRequest $request)
	{
        if(C('enabled_register')=='off'){

            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, "注册功能已被禁用", null);

        }
		$username = $request->getParameter('username');
        $password = $request->getParameter('pwd');
        $vcode = $request->getParameter('vcode');
		$service = new RegisterService();
		$data = array(
			'username' => $username,
			'password' => passwd($password),
			'last_login_time' => date('Y-m-d H:i:s'),
			'reg_time' => date('Y-m-d H:i:s'),
            'nickname' => 'mpe_'.substr($username,5)
		);
        $this -> timeOut();
        if($vcode!=$_SESSION['mpe_member']['vcode']) {
            $this->assign("username",$username);
            $this->assign('wrong' ,L('LOGIN_VCODE_ERROR'));
            return ;
        }
		if($service->hasRegister($username))
		{
            $this->assign("username",$username);
            $this->assign('wrong' ,L('MEMBER_MOBILE_UNIQUE'));
			return ;
		}
		if($service->register($data))
		{
            unset($_SESSION['mpe_member']['vcode']);
            unset($_SESSION['mpe_member']['time']);
			//header('Location:'.url('/member/login/index').'?dir='.$_SERVER['HTTP_REFERER']);
			$service = new LoginService();
            if($service -> login($username,$password)){
                header('Location:'.url('/member/index/index'));
            }
            //exit(0);
		}
		else{
		    $this->assign("username",$username);
            $this->assign('wrong',L('REGISTER_ERROR'));
			return ;
		}

	}

    /**
     * 发送注册信息
     * @param HttpRequest $request
     */
    public function getSMS(HttpRequest $request){

        //如果没有开启短信服务
        if( C('sms_open') != "on" ){
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, "短信服务未开启", null);
        }
        $mobile = $request -> getParameter('mobile');
        $flag = $request -> getParameter('msgType');
        if(!preg_match('/^\d{11}$/' , $mobile) ){
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, "请输入正确的手机号", null);
        }
        $this -> checkTimeOut();
        $_SESSION['mpe_member']['time'] = time();
        $code = rand(1000,9999);
        Session::start();
        $_SESSION['mpe_member']['vcode'] = $code;
        if( $flag == "2" ) {
            $memberService = Beans::get("member.member.service");
            if( $memberService -> count(array("username"=>$mobile,"del_status"=>0)) <=0 ){
                AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, "该号码未注册过", null);
            }
            //修改登录密码
            $rule = '修改登录密码验证码规则';
            $codeArray = array('验证码' =>$code);
            $smsService = Beans::get("message.messageRemind.service");
            $res = $smsService->commandBySmsRemind($rule, $codeArray,"",$mobile);
            if ( $res ) {
                Log::info("忘记密码验证码发送成功，发送到{$mobile}上，验证码：{$code}");
                AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS, "发送成功", null);
            }else{
                AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"发送失败，请重试！",null);
            }
        } else {
            $site = C('site_name');
            $template = "注册验证码：{$code}，您正在注册成为{$site}会员，感谢您的支持！（此验证码5分钟内有效）";//从余良处获得模板
            $service = Beans::get("message.sms.service");
            $result = $service->send($mobile, $template);
            if ($result) {
                Log::info("注册验证码发送成功，发送到{$mobile}上，验证码：{$code}");
                AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS, "发送成功", null);
            } else {
                AjaxResult::ajaxResult(AjaxResult::OP_SUCCESS, "发送失败，请重试！", null);
            }
        }
    }

    /**
     * 校验手机号码唯一性
     * @param HttpRequest $request
     */
    public function checkMobile(HttpRequest $request) {
        $username = $request -> getParameter('username');
        $service = new RegisterService();
        if($service->hasRegister($username)) {
            die("false");
        }else {
            die("true");
        }
    }

    /**
     * 重复发送手机短信时间
     */
    protected function checkTimeOut(){
        $wait = time() - $_SESSION['mpe_member']['time'];
        if( $wait < 120){
            $seconds = 120 - $wait;
            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE,"请等待{$seconds}秒后再尝试发送",null);
        }
    }
}
